package shell.listener;

import inabit.base.RuleBase;
import inabit.data.Rule;
import inabit.utils.RuleStringFormat;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import shell.view.windows.RulesPanel;
/**@author Rafael Rocha*/
public class RemoveRulesListener implements ActionListener{
	private JList rulesList;
	private RuleBase rb;
	private RulesPanel rulesPanel;
	private RuleStringFormat ruleFormat;
	
	private JList deletedRulesList;
	private DefaultListModel deletedRulesListModel;
	
	public RemoveRulesListener(RulesPanel panel, JList rulesList, RuleStringFormat ruleFormat, RuleBase rb) {
		this.rulesPanel = panel;
		this.rulesList = rulesList;
		this.rb = rb;
		this.ruleFormat = ruleFormat;
		
		deletedRulesListModel = new DefaultListModel();
		deletedRulesList = new JList(deletedRulesListModel);
	}
	
	public void actionPerformed(ActionEvent e) {
		List<Rule> deletedRules = new ArrayList<Rule>();
		
		for(Object str : rulesList.getSelectedValues()){
			String s = str.toString();
			String id = ruleFormat.getID(s);
			if(rb.containsRule(id)) {
				deletedRules.add(rb.getRule(id));
				deletedRulesListModel.addElement(id);
			}
		}
		
		if(!deletedRules.isEmpty()) {
			
			JScrollPane pane = new JScrollPane(deletedRulesList);
			
			JPanel panel = new JPanel();
			panel.setLayout(new GridBagLayout());
			GridBagConstraints c = new GridBagConstraints();
			c.gridx = 0;
			c.gridy = 0;
			c.weighty = 0;
			c.fill = GridBagConstraints.HORIZONTAL;
			panel.add(new JLabel("Tem certeza que deseja deletar as seguintes regras?"), c);
			c.gridy++;
			c.weighty = 1;
			c.fill = GridBagConstraints.BOTH;
			panel.add(pane, c);
			
			
			int option = JOptionPane.showConfirmDialog(null, panel, "Deletar regras", JOptionPane.YES_NO_OPTION);
			
			if(option == JOptionPane.YES_OPTION){
				rb.removeRules(deletedRules);
				this.rulesPanel.update();
			}
			
		}
		deletedRulesListModel.removeAllElements();
	}
}
